package com.project.class4_8.proxy1.util;

import com.project.class4_8.proxy1.dao.IRoomDao;
import com.project.class4_8.proxy1.dao.IUserDao;

import java.io.File;
import java.util.HashMap;
import java.util.Map;

public class DaoFactory {
    private static Map<Class,Object> classMap = new HashMap<>();
    static{
        File dirFile = new File("C:\\javaseHigh\\src\\com\\project\\class4_8\\proxy1\\dao\\impl");
        File[] fileArray = dirFile.listFiles();

        try {
            for (File f : fileArray) {
                if (f.isFile() && f.getName().endsWith(".java")) {
                    //得到类的全路径
                    String classPath = "com.project.class4_8.proxy1.dao.impl."
                            + f.getName().substring(0, f.getName().length() - 5);

                    //加载类，得到类模版
                    Class c = Class.forName(classPath);
                    //得到该类实现的接口
                    Class interfaceClass = c.getInterfaces()[0];
                    //产生该类的对象
                    Object obj = c.getConstructor().newInstance();
                    classMap.put(interfaceClass,obj);
                }
            }
//            System.out.println(classMap);
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    /**
     * 根据接口，得到实现接口的实现类对象
     * @param interfaceClass 接口
     * @return 实现类对象
     */
    public static Object getDao(Class interfaceClass){
        return classMap.get(interfaceClass);
    }

    public static void main(String[] args) {
        Object obj1 = DaoFactory.getDao(IUserDao.class);
        Object obj2 = DaoFactory.getDao(IRoomDao.class);
        System.out.println(obj1+"    "+obj2);
    }

}
